<template>
	<view class="live-container">
		<view v-if="['LIVE'].includes(liveInfo.status)" class="video-container">
			<!-- 视频播放器 -->
			<Video v-if="isLive" class="video-player" ref="videoPay" :poster="posterUrl" object-fit="cover" :controls="false"
				preload="auto" x-webkit-airplay="true" x5-video-player-type="h5-page" webkit-playsinline="true"
				playsInline></Video>
			<view v-if="!isPlay&&isLive" class="play" @click="play">
				<image src="./img/play.png"></image>
			</view>
			<view v-if="isLoading&&isLive" class="videoLoading">
				<p>视频加载中...</p>
			</view>
			<div v-if="liveError&&isPlay&&isLive" class="videoError">
				<div class="videoErrorBox">
					<div class="veIcon">❌</div>
					<p style="margin-bottom: 16px;">{{liveError}}</p>
					<button class="veBtn" @click="retry">重新加载</button>
				</div>
			</div>
			<!-- 顶部用户信息 -->
			<!-- <view class="user-info">
				<view class="user-avatar">
					<image :src="userAvatar" class="avatar-img"></image>
				</view>
				<view class="user-details">
					<text class="username">{{ username }}</text>
					<text class="follower-count">{{ followerCount }}</text>
				</view>
				<view class="follow-btn">
					<text class="follow-icon">+</text>
				</view>
			</view> -->
		
		
			<!-- 关闭按钮 -->
			<!-- <view v-if="isLive" class="close-btn" @click="closeLive">
				<text class="close-icon">×</text>
			</view> -->
		
			<!-- 浮动爱心 -->
			<view class="floating-hearts">
				<view v-for="(heart, index) in floatingHearts" :key="index" class="heart" :style="heart.style">
					<image src="./img/heart.png" mode="aspectFit" />
				</view>
			</view>
		
			<!-- 发言浮层动画：收到发言时向上飘并消失 -->
			<!-- <view class="speak-float-layer">
				<view v-for="item in speakFloatList" :key="item.id" class="speak-float-item">
					<text class="chat-username">{{item.nickname}}:</text>
					<text class="chat-content">{{item.content}}</text>
				</view>
			</view> -->
		
		
			<!-- 聊天区域 -->
			<view class="chat-area">
				<!-- <view class="chat-hint" v-if="isChatPaused">
					<text class="hint-text">触摸继续滚动</text>
				</view> -->
				<view class="chat-container">
					<view v-for="(message,id) in list" :key="id">
						<template v-if="message.ext">
							<!-- <view class="chat-bubble red_claim" v-if="message.ext.biz_type==='red_claim'">
								<view class="speak">
									<image class="avatar" :src="message.ext.avatar_url||userAvatar" mode="aspectFill" />
									<text class="chat-username">{{message.ext.nickname||'***'}}:</text>
									<text class="chat-content">领取了🧧</text>
								</view>
							</view>
							<view class="chat-bubble order" v-if="message.ext.biz_type==='order'">
								<view class="speak">
									<image class="avatar" :src="message.ext.avatar_url||userAvatar" mode="aspectFill" />
									<text class="chat-username">{{message.ext.nickname||'***'}}:</text>
									<text class="chat-content">下单了</text>
								</view>
							</view> -->
							<view class="chat-bubble" v-if="message.ext.biz_type==='speak'">
								<view class="speak">
									<image class="avatar" :src="message.ext.avatar_url||userAvatar" mode="aspectFill" />
									<text class="chat-username">{{message.ext.nickname||'***'}}:</text>
									<text class="chat-content">{{ message.msg }}</text>
								</view>
							</view>
						</template>
					</view>
				</view>
			</view>
		</view>
		<!-- 公告、广播 -->
		<view v-if="positionMessageBroadcast.length>0||positionMessageNotice.length>0" class="position">
			<view class="card" v-if="positionMessageNotice.length>0">
				<view class="box">
					<view class="font">公告</view>
					<view class="list" v-for="(item,id) in positionMessageNotice" :key="id">
						{{item.msg}}
					</view>
				</view>
			</view>
			<view class="card" v-if="positionMessageBroadcast.length>0">
				<view class="box">
					<view class="font">广播</view>
					<view class="list" v-for="(item,id) in positionMessageBroadcast" :key="id">
						{{item.msg}}
					</view>
				</view>
			</view>
		</view>
		<!-- 飘窗，红包，下单 -->
		<view class="bay-window">
			<view v-for="item in claimList" :key="`b_${item.id}`" class="box" :data-id="item.id">
				<view class="animation"  :key="`cb_${item.id}_${item.timestamp || 0}`">
					<image class="avatar" :src="item.avatar_url" />
					<view class="info">
						<view class="name">
							<text class="n">{{item.nickname}}</text>
							<text class="s">{{item.status}}</text>
						</view>
						<view class="title">{{item.title}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 用户进放房间 -->
		<!-- <view class="bay-window">
			<view class="box">
				<view class="animation">
					<image class="avatar" :src="item.avatar_url" />
					<view class="info">
						<view class="name">
							<text class="n">{{item.nickname}}</text>
							<text class="s">{{item.status}}</text>
						</view>
						<view class="title">{{item.title}}</view>
					</view>
				</view>
			</view>
		</view> -->
		<!-- 橱窗弹窗 -->
		<view class="red_showcase" v-if="showRedShowcase">
			<image :src="redShowcase.coverImage" mode="aspectFit" />
			<view class="rp-close" @click="showRedShowcase=false"><image src="/static/img/close.png" class="close"></image></view>
			<view class="openRed" @click.self="openPayBottom"></view>
		</view>
		<!-- 红包弹窗 -->
		<view class="rp-mask" v-if="showRedPacket">
			<view class="rp-dialog" :style="`width: ${redPacket.coverRatio}%`">
				<view v-if="redTime>0&&!isOpenRed" class="time">{{redTime}} 秒</view>
				<image v-if="!isOpenRed" :src="redPacket.coverImage" class="img" mode="widthFix"></image>
				<image v-if="isOpenRed" :src="redPacket.redImageUrl" class="img" mode="widthFix"></image>
				<view class="rp-close" @click="closeRedPacket"><image src="/static/img/close.png" class="close"></image></view>
				<view class="openRed" @click.self="openRedPacket"></view>
			</view>
		</view>
		<!-- 支付弹窗 -->
		<view>
			<uni-popup ref="popup" background-color="#fff" :mask-click="false">
				<view class="popup-pay" >
					<image src="/static/img/close.png" class="close" @click="payClose"></image>
					<view class="top">支付方式</view>
					<view class="radio">
						<view class="df" :class="payType=='wx'?'on':''" @click="paySel('wx')">
							<image class="icon" src="@/static/img/wx.png" />
							<view class="title">微信支付</view>
						</view>
						<!-- <view class="df" :class="payType=='zfb'?'on':''" @click="paySel('zfb')">
							<image class="icon" src="@/static/img/zfb.png" />
							<view class="title">支付宝支付</view>
						</view> -->
						<view class="tips">当前报名人数较多，如出现异常提示，请再次尝试或联系班主任</view>
					</view>
					<view class="popupFooter">
						<view class="info"> 
							<text class="label">价格：</text>
							<text class="price">￥{{courseInfo.payPrice}}元</text>
							<text class="original">原价：{{courseInfo.price}}元</text>
						</view>
						<view class="btn" @click="goPay">立即支付</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<!-- 开播倒计时 -->
		<view v-if="liveInfo.status=='SCHEDULED'" class="scheduled-time">
			<view class="tn">距离开播还有</view>
			<view class="tm">{{getCountdownTime}}</view>
		</view>
		<!-- 底部操作栏 -->
		<view class="bottom-bar" :class="isLive?'bar-live':''">
			<view v-if="!['ENDED','CANCELED'].includes(liveInfo.status)" class="input-area">
				<input class="uni-input sendInput" placeholder='来说点什么吧' v-model="inputVal" confirm-type="发送"
					@confirm="sendMessage" />
				<!-- <text class="input-placeholder">说点什么?</text> -->
			</view>
			<view v-if="!['ENDED','CANCELED'].includes(liveInfo.status)" class="action-buttons">
				<view class="action-btn" @click="sendMessage">
					<image src="@/static/img/send.png" />
				</view>
			</view>
		</view>
		<view v-if="isLive" class="refresh" @click="retry">刷新</view>
	</view>
</template>

<script>
	import FlvJs from 'flv.js';
	import MiniCore from "easemob-websdk/miniCore/miniCore";
	import * as chatroomPlugin from "easemob-websdk/chatroom/chatroom";
	import * as contactPlugin from "easemob-websdk/contact/contact";
	import {isWeChatBrowser} from '@/utils/platform.js'
	import {getLive,getLiveToken,getIm} from '@/api/live.js'
	import {payOrder,createOrder,claimRedpack} from '@/api/contract.js'
	import {wxPay} from '@/utils/wx.js'
	//类型，speak=发言，red_pop=弹窗红包，red_showcase=橱窗红包；red_claim=红包领取 order=下单，notice=公告； broadcast=广播；notice_close=公告关闭； broadcast_close=广播关闭；system：系统消息，memberPresence：成员加入
	let miniCore = null
	//发布订阅者的 eventName
	const EventName = 'chatroom'
	export default {
		name: 'LivePage',
		data() {
			return {
				isDebug:false,//是否为测试
				liveRoomId:'',//直播id
				roomCode:'', //直播间code
				liveInfo:{},  //直播详情
				isLive:false,//直播是否正在进行时
				countdownTime:0,//直播倒计时-未开始
				videoUrl: '', // 直播流地址
				posterUrl: '', // 直播封面图
				userAvatar: '', // 用户头像
				username: '',
				payType:'wx',  //支付类型
				followerCount: '1263',
				popularityCount: '5324670',
				floatingHearts:[],
				isLiked: false,
				isChatPaused: false,
				isLoading: false,
				userInfo: {}, //用户信息
				cdnFlvPlayer: null, //直播Flv对象
				liveError: null, //直播加载错误提示
				videoRef: null, //video对象
				isPlay: false, //是否播放，刚进入页面不播放，同时解决自动播放与静音冲突
				isConn: false, //im是否连接
				memberCount: 0, //房间人数
				chatRoomId: null, //im的房间id
				imUserId: null, //im的用户id
				imToken: null, //im的token
				list: [], //消息列表
				speakFloatList: [], //短暂展示的发言气泡（向上消失）
				positionMessageNotice: [], //公告数据
				positionMessageBroadcast: [],//广播数据
				bizType:'',//消息类型
				showRedPacket: false,  //红包弹窗
				redPacket: {}, //红包信息
				isOpenRed:false,//是否打开红包
				redTime:0,//红包倒计时
				redTimeFn:null, //红包倒计时方法
				claimRedId:'',//领取的红包id
				courseInfo:{}, //关联课程信息
				claimList:[],  //飘窗数据
				redShowcase:{},//橱窗信息
				showRedShowcase:false,//橱窗弹窗
				inputVal: '', //消息输入值
				isInit:false,  //是否初始化，解决授权登录后，没有掉直播接口的问题
			}
		},
		computed:{
			getCountdownTime(){
				// 计算时分秒
				if(this.countdownTime>=0){
					const hours = Math.floor(this.countdownTime / 3600);
					const minutes = Math.floor((this.countdownTime % 3600) / 60);
					const seconds = this.countdownTime % 60;
					return `${hours<10?'0':''}${hours}:${minutes<10?'0':''}${minutes}:${seconds<10?'0':''}${seconds}`
				}else{
					return '00:00:00'
				}
				
			}
		},
		mounted() {
			const _this=this;
			let query = new URLSearchParams(window.location.search);
			this.roomCode=query.get('q');
			this.isDebug=query.get('debug')?true:false;
			this.userInfo=this.$Cache.get('userInfo')?JSON.parse(this.$Cache.get('userInfo')):{};
			this.getLive()
		},
		methods: {
			//支付类型选择
			paySel(type){
				this.payType=type;
			},
			//下订单
			async goPay() {
				const _this=this;
				const res=await createOrder({
					"courseCode":_this.courseInfo.courseCode,
					"quantity":1,
					couponId:_this.claimRedId,
					liveRoomId:_this.liveRoomId,
				})
				const payRes= await payOrder({
					provider:'WECHAT',
					orderSn:res.data.orderSn,
					tradeType:'JSAPI',
				})
				if(isWeChatBrowser()){
					wxPay(payRes?.data?.prepayParams,(cRes)=>{
						if(cRes?.errMsg=='chooseWXPay:ok'){
							_this.$refs.popup.close()
							uni.showToast({
								title: '支付成功',
								duration: 2000
							});
						}
					})
				}else{
					window.location.href=payRes?.data?.payUrl;
				}
			},
			payClose(){
				this.$refs.popup.close()	
			},
			//发送文本消息
			async sendTextMsg(c) {
				const _this = this;
				const ext = {
					avatar_url: _this.userInfo ? _this.userInfo.avatarUrl : '',
					nickname: _this.userInfo ? _this.userInfo.realName : '',
					role: 'user', //user：普通用户
					biz_type: 'speak', //类型，speak=发言，red_packet=红包，order=下单，system：系统消息，memberPresence：成员加入
				}
				const option = {
					chatType: "chatRoom", //聊天室
					type: "txt", //文本消息
					to: this.chatRoomId, //聊天室ID
					msg: c, //消息
					ext: ext
				};
				try {
					const msg = miniCore.Message.create(option);
					await miniCore.send(msg)
					console.log("发送成功", msg);
					//自己发送的消息，自己不会接收
					this.list = [...this.list, msg]
				} catch (err) {
					console.log(err)
					console.log("发送失败", err);
				}
			},
			//发送
			sendMessage() {
				if (this.inputVal == '') {
					return
				} else {
					this.sendTextMsg(this.inputVal)
					this.inputVal = ''
				}
			},
			//im初始化
			async imInit() {
				const _this = this;
				miniCore.addEventHandler(EventName, {
					onConnected: async () => {
						console.log("连接成功");
						_this.isConn = true;
					},
					// 自 4.8.0 版本，`onDisconnected` 事件新增断开原因回调参数, 告知用户触发 `onDisconnected` 的原因。
					onDisconnected: () => {
						console.log("连接断开");
					},
					onReconnecting: () => {
						console.log("重连中");
					},
					onTextMessage: (message) => {
						console.log("收到文本消息", message);
						_this.onTextMessage(message)
					},
					onChatroomEvent: (e) => {
						_this.sysEvent(e)
					}
				});
				try {
					const res = await getIm({
						roomId:_this.liveRoomId
					})
					_this.chatRoomId = res.data.chatroomId;
					_this.imUserId = res.data.imUserId;
					_this.imToken = res.data.imToken
					//事件监听
					const joinObj = JSON.stringify({
						userId:_this.userInfo?_this.userInfo.userId:'',
						avatar_url: _this.userInfo ? _this.userInfo.avatarUrl : '',
						nickname: _this.userInfo ? _this.userInfo.wechatNickname||_this.userInfo.realName : '',
						role: 'user', //user：普通用户
						biz_type: 'memberPresence', //类型，speak=发言，red_packet=红包，order=下单，system：系统消息，memberPresence：成员加入
					})
		
					try {
						// 登录
						await miniCore.open({
							username: _this.imUserId,
							accessToken: _this.imToken,
						})
						//连接成功
						this.isConn = true;
						//加入聊天室
						miniCore.chatroom.joinChatRoom({
							roomId: _this.chatRoomId,
							// 加入聊天室时携带的扩展信息
							ext: joinObj,
							// 加入聊天室时，是否退出已加入的聊天室
							leaveOtherRooms: true
						})
						_this.historyMsg()
					} catch (err) {
						//已经登录
						if (err.type === 208) {
							//连接成功
							this.isConn = true;
							//加入聊天室
							miniCore.chatroom.joinChatRoom({
								roomId: _this.chatRoomId,
								// 加入聊天室时携带的扩展信息
								ext: joinObj,
								// 加入聊天室时，是否退出已加入的聊天室
								leaveOtherRooms: true
							})
							_this.historyMsg()
						}
		
					}
		
		
				} catch (err) {
					console.log(err)
				}
		
			},
			//获取历史消息
			async historyMsg() {
				const resMsg = await miniCore.contact.getHistoryMessages({
					targetId: this.chatRoomId,
					chatType: 'chatRoom',
					pageSize: 10, // 每次获取的消息数量，取值范围为 [1,50]，默认值为 `20`。
					searchDirection: 'up', // 消息搜索方向。`up` 表示按消息时间戳递减的方向获取，即先获取最新消息；`down` 表示按消息时间戳递增的方向获取，即先获取最老的消息。
					// 查询的起始消息 ID。若该参数设置为 `-1`、`null` 或空字符串，从最新消息开始。
					cursor: -1
				});
				const temp = resMsg.messages.sort((a, b) => a.time - b.time)
				this.list = temp;
			},
			//消息事件
			sysEvent(e) {
				const _this = this;
				switch (e.operation) {
					// 解除聊天室一键禁言。聊天室所有成员（除操作者外）会收到该事件。
					case 'unmuteAllMembers':
						break;
						// 聊天室一键禁言。聊天室所有成员（除操作者外）会收到该事件。
					case 'muteAllMembers':
						break;
						// 将成员移出聊天室白名单。被移出的成员收到该事件。
					case 'removeAllowlistMember':
						break;
						// 添加成员至聊天室白名单。被添加的成员收到该事件。
					case 'addUserToAllowlist':
						break;
						// 删除聊天室公告。聊天室的所有成员会收到该事件。
					case 'deleteAnnouncement':
						break;
						// 更新聊天室公告。聊天室的所有成员会收到该事件。
					case 'updateAnnouncement':
						break;
						// 更新聊天室详情。聊天室的所有成员会收到该事件。
					case 'updateInfo':
						break;
						// 解除对指定成员的禁言。被解除禁言的成员会收到该事件。
					case 'unmuteMember':
						break;
						// 有成员被移出聊天室黑名单。被移出的成员会收到该事件。
					case 'unblockMember':
						break;
						// 禁言指定成员。被禁言的成员会收到该事件。
					case 'muteMember':
						break;
						// 有用户加入聊天室。聊天室的所有成员（除新成员外）会收到该事件。
					case 'memberPresence':
						// 当前聊天室在线人数,有人进入房间
						_this.memberCount = e?.memberCount || 0;
						const option = {
							chatType: "chatRoom", //聊天室
							type: "txt", //文本消息
							to: _this.chatRoomId, //聊天室ID
							msg: '', //消息
							ext: typeof e.ext == 'string' ? JSON.parse(e.ext) : e.ext
						};
						const msg = miniCore.Message.create(option);
						_this.list = [..._this.list, msg]
						break;
						// 主动退出聊天室。聊天室的所有成员（除退出的成员）会收到该事件。
					case 'memberAbsence':
						// 当前聊天室在线人数
						_this.memberCount = e?.memberCount || 0;
		
						break;
						// 有成员被移出聊天室。被踢出聊天室的成员会收到该事件。   
					case 'removeMember':
						break;
						// 有成员修改/设置聊天室自定义属性，聊天室的所有成员会收到该事件。
					case 'updateChatRoomAttributes':
						break;
						// 有成员删除聊天室自定义属性，聊天室所有成员会收到该事件。
					case 'removeChatRoomAttributes':
						break;
					default:
						break;
				}
			},
			//接收消息
			onTextMessage(message) {
				const _this=this;
				this.list = [...this.list, message]
				// 业务：根据扩展字段区分消息类型
				const ext = message.ext || {}
				const biz = ext.biz_type
				_this.bizType=biz;
				console.log('onTextMessage===', message, biz)
				//用户进入房间
				if(biz==='memberPresence'){
					console.log(ext,biz)
				}
				//广播
				if (biz === 'broadcast') {
					//暂停广播
					if(ext.type=="hidden"){
						_this.positionMessageBroadcast=_this.positionMessageBroadcast.filter(item=>item.code!=ext.code)
					}else{
						_this.positionMessageBroadcast.push({
							...ext,
							msg: message.msg,
							biz,
							id:message.id
						})
					}
					
				}
				//公告
				if (biz === 'notice') {
					//暂停公告
					if(ext.type=="hidden"){
						_this.positionMessageNotice=_this.positionMessageNotice.filter(item=>item.code!=ext.code)
					}else{
						this.positionMessageNotice.push({
							...ext,
							msg: message.msg,
							biz,
							id:message.id
						})
					}
				}
				
				//橱窗红包
				if(biz=='red_showcase'){
					_this.redShowcase={
						...ext,
						coverImage:`${ext?.data?.domainUrl}/${ext?.data?.coverImage}`,
						msg: message.msg,
						biz
					}
					_this.courseInfo={
						courseCode:ext.data.courseCode,
						courseId:ext.data.courseId,
						price:ext.data.price,
						payPrice:ext.data.payPrice,
						toolRedpayId:ext.data.toolRedpayId
					}
					_this.showRedShowcase = true
				}
				//弹窗红包
				if (biz === 'red_pop') {
					_this.showRedPacket = true;
					_this.isOpenRed=false;
					_this.redPacket={
						...ext,
						coverImage:`${ext?.data?.domainUrl}/${ext?.data?.coverImage}`,
						redImageUrl:`${ext?.data?.domainUrl}/${ext?.data?.redImageUrl}`,
						coverRatio:ext?.data?.coverRatio||66,
						msg: message.msg,
						biz
					}
					_this.courseInfo={
						courseCode:ext.data.courseCode,
						courseId:ext.data.courseId,
						price:ext.data.price,
						payPrice:ext.data.payPrice,
						toolRedpayId:ext.data.toolRedpayId
					}
					_this.redTime=ext?.data?.displaySeconds||10;
					_this.redTimeFn=setInterval(()=>{
						_this.redTime--;
						if(_this.redTime<=0){
							_this.showRedPacket=false;
							_this.isOpenRed=false;
							clearInterval(_this.redTimeFn)
						}
					},1000)
				}
				//飘窗-红包领取，下单
				if (biz === 'red_claim'||biz === 'order'){
					const newItem={
						nickname:ext.nickname,
						avatar_url:ext.avatar_url,
						biz_type:biz,
						title:ext?.data?.title,
						status:ext?.data.status,
						id:message?.id,
						timestamp: Date.now()
					}
					if(_this.claimList.length>=3){
						_this.claimList=_this.claimList.slice(0,3)
						_this.$set(_this, 'claimList', [newItem, ..._this.claimList.slice(0, 2)]);
					}else{
						_this.$set(_this, 'claimList', [newItem, ..._this.claimList]);
					}
				}
				//直播结束
				if(biz==='live_stop'){
					_this.retry()
				}
			},
			// 临时展示发言浮层并上浮消失
			pushSpeakFloat(item) {
				this.speakFloatList.push(item)
				setTimeout(() => {
					this.speakFloatList = this.speakFloatList.filter(i => i.id !== item.id)
				}, 2500)
			},
			//点击红包弹窗
			async openRedPacket(){
				if(this.isOpenRed){
					//关闭弹窗
					this.showRedPacket=false;
					this.isOpenRed=false;
					//打开付款
					this.$refs.popup.open('bottom')
				}else{
					//领取红包
					const res=await claimRedpack({redpackItemId:this.courseInfo.toolRedpayId,liveRoomId:this.liveRoomId})
					this.claimRedId=res.data.redpackReceiveId;
					//打开优惠卷
					this.isOpenRed=true
					//关闭定时器
					clearInterval(this.redTimeFn)
				}
				
			},
			//点击红包飘窗-打开付款弹窗
			async openPayBottom(){
				//打开付款
				this.$refs.popup.open('bottom');
				this.showRedShowcase=false;
			},
			// 关闭红包
			closeRedPacket() {
				this.showRedPacket = false;
				this.isOpenRed=false;
				clearInterval(this.redTimeFn)
			},
			
			//手动点击播放
			play() {
				if (this.videoRef) {
					this.isPlay = true;
					this.videoRef.play().then(() => {})
				}
			},
			//倒计时-直播未开始
			countdown(){
				const _this=this;
				const temp=setInterval(()=>{
					_this.countdownTime--
					if(_this.countdownTime<=0){
						clearInterval(temp)
						_this.isLive=true;
						_this.getLive()
					}
				},1000)
			},
			//获取直播地址
			async getLive() {
				const _this = this;
				try{
					const liveRes=await getLive(_this.roomCode)
					_this.isInit=true;
					_this.liveRoomId=liveRes.data.liveRoomId;
					_this.liveInfo=liveRes.data;
					_this.isLive=['LIVE','PAUSED'].includes(liveRes.data.status);
					//直播未开始
					if(liveRes.data.status=='SCHEDULED'){
						_this.countdownTime=liveRes.data.distanceToStart;
						_this.countdown()
					}
					//直播进行中
					if(['LIVE','SCHEDULED','PAUSED'].includes(liveRes.data.status)||_this.isDebug){
						// _this.startFloatingHearts()
						const res = await getLiveToken({
							roomId:_this.liveRoomId
						})
						//获取imkey
						miniCore = new MiniCore({
							appKey: res.data.ak,
						});
						//按需加载，注册组件
						miniCore.usePlugin(chatroomPlugin, "chatroom");
						miniCore.usePlugin(contactPlugin, "contact");
						setTimeout(() => {
							_this.imInit()
						}, [500])
								
						_this.videoRef = _this.$refs.videoPay;
						//判断是否支持flv格式
						if (FlvJs.isSupported()) {
							_this.videoUrl = res.data.zego.rtmpPullFlv;
							// _this.videoUrl='http://play-hw1.zhiweidance.com/live/Xd6Xp670.flv'
							_this.flvVideo()
							return
						} else {
							_this.videoRef.src = res.data.zego.rtmpPullHls
							_this.videoUrl = res.data.zego.rtmpPullHls
						}
					}
					//直播暂停中
					if(liveRes.data.status==='PAUSED'){
						uni.showLoading({
							icon:null,
							title: '直播中断'
						});
					}
					//直播结束或取消
					if(['ENDED','CANCELED'].includes(liveRes.data.status)){
						uni.showLoading({
							icon:null,
							title: '直播已结束'
						});
					}
					
				}catch(err){
					//解决登录后，写token需要时间,但请求接口里还没写完，获取不到的问题
					if(err.code===401&&!_this.isInit){
						setTimeout(()=>{
							_this.getLive()
						},500)
					}
				}
				
			},
			//flv格式直播
			async flvVideo(isAgain = false) {
				const _this = this;
				try {
					_this.isLoading = true;
					_this.liveError = null;
					// 先销毁之前的播放器实例（如果存在）
					if (_this.cdnFlvPlayer) {
						_this.cdnFlvPlayer.destroy();
						_this.cdnFlvPlayer = null;
					}
					_this.cdnFlvPlayer = FlvJs.createPlayer({
						type: 'flv',
						isLive: true,
						url: _this.videoUrl,
					});
					_this.cdnFlvPlayer.on(FlvJs.Events.ERROR, (err) => {
						console.error('FLV播放错误:', err);
						_this.liveError = '加载失败，请检查网络连接或刷新页面'
						_this.isLoading = false;
					});
					// 改用更可靠的事件监听
					_this.cdnFlvPlayer.on(FlvJs.Events.METADATA_ARRIVED, () => {
						console.log('FLV元数据加载完成');
						_this.isLoading = false;
					});
					_this.cdnFlvPlayer.on(FlvJs.Events.STATISTICS_INFO, () => {
						// console.log('加载成功')
						// 统计信息事件定期触发，表明流正在工作,会不断执行
						if (_this.isLoading) {
							_this.isLoading = false;
						}
					});
					_this.cdnFlvPlayer?.on(FlvJs.Events.LOADING_COMPLETE, function() {
						//监听到失败，比如直播流断了，需要整个重新加载一下
						console.error('LOADING_COMPLETE');
						_this.liveError = '加载失败，请检查网络连接或刷新页面'
						_this.isLoading = false;
					});
					try {
						_this.cdnFlvPlayer?.attachMediaElement(_this.videoRef);
						_this.cdnFlvPlayer?.load();
						//这里打开后，业务加载就会自动播放
						// _this.cdnFlvPlayer?.play();
						//是否重新加载
						if (isAgain) {
							_this.play()
						}
					} catch (err) {
						console.error('播放失败:', err);
						_this.liveError = '播放失败，尝试回退到HLS'
					}
		
				} catch (err) {
					console.log(err)
				}
			},
			//重新加载
			retry() {
				this.liveError = null;
				this.getLive()
			},
		
			closeLive() {
				uni.navigateBack()
			},
		
			shareLive() {
				uni.showShareMenu({
					withShareTicket: true,
					menus: ['shareAppMessage', 'shareTimeline']
				})
			},
		
			likeLive() {
				this.isLiked = !this.isLiked
				// 添加点赞动画
				if (this.isLiked) {
					this.addFloatingHeart()
					uni.showToast({
						title: '点赞成功',
						icon: 'success'
					})
				}
			},
		
			addFloatingHeart() {
				const heart = {
					style: {
						left: Math.random() * 200 + 50 + 'rpx',
						animationDelay: '0s'
					}
				}
				this.floatingHearts.push(heart)
		
				// 3秒后移除爱心
				setTimeout(() => {
					const index = this.floatingHearts.indexOf(heart)
					if (index > -1) {
						this.floatingHearts.splice(index, 1)
					}
				}, 3000)
			},
		
			startFloatingHearts() {
				const _this=this;
				
				setInterval(() => {
					if (_this.floatingHearts.length < 5) {
						_this.addFloatingHeart()
					}
				}, 2000)
			},
		
			pauseChatAnimation() {
				this.isChatPaused = true
			},
		
			resumeChatAnimation() {
				this.isChatPaused = false
			}
		}
		
	}
</script>
<style lang="scss" scoped>
	@import './live.scss';
</style>